package com.bytecodes.eaulas.comun;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import com.bytecodes.eaulas.comun.servicios.EAulasServiciosImpl;
import com.bytecodes.eaulas.comun.servicios.EAulasServiciosInterface;
import com.bytecodes.eaulas.comun.servicios.TDSLanguageUtils;

/**
 * Clase Servidor
 * 
 * @author David Fern�ndez G�mez
 * @version 1.0
 */

public class Servidor extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JLabel Stat = null;
	private JButton Iniciar = null;
	private JButton Parar = null;

	private boolean strt = false;
	private EAulasServiciosImpl eaulasServicios = null;

	/**
	 * Iniciar (Arranca el servidor)
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getIniciar() {
		if (Iniciar == null) {
			Iniciar = new JButton();
			Iniciar.setLocation(new Point(15, 46));
			Iniciar.setSize(new Dimension(140, 20));
			Iniciar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try {
						arrancaServidor();
					} catch (RemoteException eR) {
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.rmi"),
								TDSLanguageUtils.getMessage("err.servidor"),
								JOptionPane.ERROR_MESSAGE);
					} catch (ConnectException eCe) {
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.rmi"),
								TDSLanguageUtils.getMessage("err.servidorr"),
								JOptionPane.ERROR_MESSAGE);
					} catch (MalformedURLException eMurl) {
						// path incorrecte
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.rmi"),
								TDSLanguageUtils.getMessage("err.servidor"),
								JOptionPane.ERROR_MESSAGE);
					} catch (Exception eV) {
						// error desconegut
						JOptionPane.showMessageDialog(null, eV.toString(),
								TDSLanguageUtils.getMessage("err.errorGen"),
								JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return Iniciar;
	}

	/**
	 * This method initializes Parar (Atura el servidor)
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getParar() {
		if (Parar == null) {
			Parar = new JButton();
			Parar.setBounds(new Rectangle(223, 46, 140, 20));
			Parar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try {
						pararServidor();
					} catch (RemoteException eRe) {
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.fi.ok"),
								TDSLanguageUtils.getMessage("err.servidor"),
								JOptionPane.ERROR_MESSAGE);
					} catch (MalformedURLException eMurle) {
						// path incorrecte
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.fi"),
								TDSLanguageUtils.getMessage("err.servidor"),
								JOptionPane.ERROR_MESSAGE);
					} catch (NotBoundException eNbe) {
						// error
						JOptionPane.showMessageDialog(null, TDSLanguageUtils
								.getMessage("err.servidor.fi"),
								TDSLanguageUtils.getMessage("err.servidor"),
								JOptionPane.ERROR_MESSAGE);
					} catch (Exception eE) {
						// error indeterminat
						JOptionPane.showMessageDialog(null, eE.toString(),
								TDSLanguageUtils.getMessage("err.errorGen"),
								JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return Parar;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Servidor thisClass = new Servidor();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setLocation(300, 100);
				thisClass.setResizable(false);
				thisClass.setVisible(true);
			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public Servidor() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		/**
		 * Comprobar que existe fichero mensajes
		 */
		boolean hiHaFitxerMessages = TDSLanguageUtils
		.setDefaultLanguage("i18n/messages");

		if (!hiHaFitxerMessages) {
			System.out
			.println("No se ha cargado el fichero de mensajes. La aplicaci�n no se puede iniciar");
			System.exit(-1);
		}
		this.setSize(450, 120);
		this.setContentPane(getJContentPane());
		this.setTitle(TDSLanguageUtils.getMessage("servidor.titulo"));
		Stat.setText("Arrancar servidor");
		Iniciar.setText(TDSLanguageUtils.getMessage("servidor.iniciar"));
		Parar.setText(TDSLanguageUtils.getMessage("servidor.parar"));
		setStat();
	}

	/**
	 * Inicializa el objeto remoto
	 * 
	 * @throws RemoteException
	 * @return void
	 */
	private void initObjecteRemot() throws RemoteException {
		strt = false;
		//
		if (eaulasServicios == null)
			eaulasServicios = new EAulasServiciosImpl();
	}

	/**
	 * Deixa el JFrame segons l'estat de la connexi�
	 * 
	 * @return void
	 */
	private void setStat() {
		if (!strt) {
			Stat.setText(TDSLanguageUtils
					.getMessage("servidor.estado.pendiente"));
			Stat.setForeground(new Color(255, 51, 51));
			Iniciar.setEnabled(true);
			Parar.setEnabled(false);
		} else {
			Stat.setText(TDSLanguageUtils
					.getMessage("servidor.estado.arrancado"));
			Stat.setForeground(new Color(51, 51, 252));
			Iniciar.setEnabled(false);
			Parar.setEnabled(true);
		}
	}

	/**
	 * Arrancada del servidor de RMI
	 * 
	 * @throws RemoteException
	 * @throws MalformedURLException
	 * @throws ConnectException
	 * @return void
	 */
	private void arrancaServidor() throws RemoteException,
	MalformedURLException, ConnectException {
//		if (eaulasServicios == null)
//		initObjecteRemot();

		EAulasServiciosInterface objRemot = new EAulasServiciosImpl();            
		// Naming.rebind("//localhost/EAulasServiciosInterface", objRemot);
		Naming.rebind("EAulasServiciosInterface", objRemot); 
//		Naming.rebind("EAulasServiciosInterface", eaulasServicios);
		strt = true;
		setStat();
	}

	/**
	 * Aturada del servidor RMI
	 * 
	 * @throws RemoteException
	 * @throws MalformedURLException
	 * @throws NotBoundException
	 * @return void
	 */
	private void pararServidor() throws RemoteException, MalformedURLException,
	NotBoundException {
		Naming.unbind("EAulasServiciosInterface");
		strt = false;
		setStat();
	}

	/**
	 * 
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			Stat = new JLabel();
			Stat.setBounds(new Rectangle(17, 8, 380, 16));
			Stat.setForeground(new Color(51, 51, 51));
			Stat.setText(TDSLanguageUtils
					.getMessage("client.missatge"));
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(Stat, null);
			jContentPane.add(getIniciar(), null);
			jContentPane.add(getParar(), null);
		}
		return jContentPane;
	}

}
